<?php

/** Check if environment is development and display errors **/

function setReporting() {
	if (DEVELOPMENT_ENVIRONMENT == true) {
		error_reporting(E_ALL);
		ini_set('display_errors','On');
	} else {
		error_reporting(E_ALL);
		ini_set('display_errors','Off');
		ini_set('log_errors', 'On');
		ini_set('error_log', ROOT.DS.'tmp'.DS.'logs'.DS.'error.log');
	}
}

/** Check for Magic Quotes and remove them **/

function stripSlashesDeep($value) {
	$value = is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value);
	return $value;
}

function removeMagicQuotes() {
	if ( get_magic_quotes_gpc() ) {
		$_GET    = stripSlashesDeep($_GET   );
		$_POST   = stripSlashesDeep($_POST  );
		$_COOKIE = stripSlashesDeep($_COOKIE);
	}
}


/** Check register globals and remove them **/

function unregisterGlobals() {
	if (ini_get('register_globals')) {
		$array = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
		foreach ($array as $value) {
			foreach ($GLOBALS[$value] as $key => $var) {
				if ($var === $GLOBALS[$key]) {
					unset($GLOBALS[$key]);
				}
			}
		}
	}
}



/*
 *  yoursite.com/controllerName/actionName/queryString
	So callHook() basically takes the URL which we have received from index.php and separates it out as $controller, 
	$action and the remaining as $queryString. $model is the singular version of $controller.
 */
function callHook() // Cat url thanh cac thanh phan can thiet: 

{
	global $url;
	$urlArray = array();
	$urlArray = explode("/", $url);
	
	$controller = $urlArray[0];
	array_shift($urlArray);
	$action = $urlArray[0];
	array_shift($urlArray);
	$queryString = $urlArray;
	
	$controllerName = $controller;
	$controller = ucwords($controller);
	$model = rtrim($controller,'s');
	$controller .= 'sController';
	$dispatch = new $controller($model,$controllerName,$queryString);
	
	if((int)method_exists($controller, $action))
		call_user_func_array(array($dispatch,$action), $queryString);
	else
	{
		
	}
	
}

/** Autoload any classes that are required **/
function __autoload($classname)
{
	if(file_exists(ROOT.DS.'library'.DS.strtolower($classname).'.class.php'))
	{
		require_once (ROOT.DS.'library'.DS.strtolower($classname).'.class.php');
	}
	elseif(file_exists(ROOT.DS.'library'.DS.strtolower($classname).'.php'))
	{
		require_once (ROOT.DS.'library'.DS.strtolower($classname).'.php');
	}
	elseif (file_exists(ROOT.DS.'application'.DS.'controllers'.DS.strtolower($classname).'.php'))
	{
		require_once (ROOT.DS.'application'.DS.'controllers'.DS.strtolower($classname).'.php');
	}
	elseif(file_exists(ROOT.DS.'application'.DS.'models'.DS.strtolower($classname).'.php'))
	{
		require_once (ROOT.DS.'application'.DS.'models'.DS.strtolower($classname).'.php');

	}
	else
	{}
}

setReporting();
removeMagicQuotes();
unregisterGlobals();
callHook();

